import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
  private headers = new HttpHeaders().set('authorization', `Bearer ${localStorage.token}`);

  constructor(private http: HttpClient,
              private router: Router) {
  }

  canActivate() {
    this.http.get<any[]>(`/api/web/v1/users/profile`, { headers: this.headers }).subscribe(data => {
      if (data['code'] !== '1000') {
        this.router.navigate(['/login']);
      }
    });
    return true;
  }
}
